package cn.nebula.music.service;

import java.sql.Time;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.nebula.music.dao.MvDAO;
import cn.nebula.music.dao.SongDAO;
import cn.nebula.music.domain.Mv;
import cn.nebula.music.domain.Song;

@Service
public class MvServiceImpl implements MvService {

	@Autowired
	private MvDAO mvDAO;

	@Autowired
	private SongDAO songDAO;

	@Override
	public Set<Mv> findAllMvs() throws Exception {
		return mvDAO.findAllMvs();
	}

	@Override
	public Set<Mv> findAllMvsOfBT() throws Exception {
		return mvDAO.findAllMvsOfBT();
	}

	@Override
	public Set<Mv> findAllMvsWP() throws Exception {
		return mvDAO.findAllMvsWP();
	}

	@Override
	public Mv findMvById(Integer id) throws Exception {
		return mvDAO.findMvById(id);
	}

	@Override
	public Mv findMvWPById(Integer id) throws Exception {
		return mvDAO.findMvWPById(id);
	}

	@Override
	public Mv findMvByResourcepath(String resourcepath) throws Exception {
		return mvDAO.findMvByResourcepath(resourcepath);
	}

	@Override
	public Set<Mv> findMvByDuration(Time duration) throws Exception {
		return mvDAO.findMvByDuration(duration);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void addMv(Mv mv) throws Exception {
		mvDAO.addMv(mv);
		if (mv.getSong() != null) {
			for (Song song : songDAO.findAllSongs()) {
				if (mv.getSong().getId().equals(song.getId())) {
					song.setMv(mv);
					songDAO.updateSong(song);
				}
			}
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateMv(Mv mv) throws Exception {
		mvDAO.updateMv(mv);
		for (Song song : songDAO.findAllSongs()) {
			if (song.getMv() != null && song.getMv().getId().equals(mv.getId())) {
				song.setMv(null);
				songDAO.updateSong(song);
			}
			if (mv.getSong() != null && mv.getSong().getId().equals(song.getId())) {
				song.setMv(mv);
				songDAO.updateSong(song);
			}
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public void deleteMvById(Integer id) throws Exception {
		for (Song song : songDAO.findAllSongs()) {
			if (song.getMv() != null && song.getMv().getId().equals(id)) {
				song.setMv(null);
				songDAO.updateSong(song);
			}
		}
		mvDAO.deleteMvById(id);
	}

}
